/**
 * 主处理函数
 * @param {Object} params - 输入参数
 * @returns {Promise<boolean>} - 返回处理结果
 */
function main(params) {
    const self = this;
    debugger
    // 解构参数
    const applyUseEndDate = params.apply_use_end.value;
    const verifyStateName = params.verify_state_name.value;
    const appointmentType = params.appointment_state_type.value;
    const id = params.id.value;

    // 如果状态是"已撤销"或"已过期"，直接返回true
    if (['已撤销', '已过期'].includes(verifyStateName)) {
        return Promise.resolve(true);
    }

    const today = new Date().toLocaleDateString();
    const dateRangeString = `${today} ~ ${applyUseEndDate}`;
    const commonParams = {
        applyUseEndDate,
        verifyStateName,
        appointmentType,
        id
    };

    // 处理预约申请（appointmentType === 1）
    if (appointmentType === 1) {
        return handleAppointmentCase(self, dateRangeString, commonParams);
    }
    // 处理取消申请（appointmentType === -1）
    else if (appointmentType === -1) {
        return handleCancellationCase(self, dateRangeString, commonParams);
    }

    return Promise.resolve(false);
}

/**
 * 处理预约申请相关逻辑
 * @param {Object} self - 上下文
 * @param {string} dateRangeString - 日期范围字符串
 * @param {Object} params - 参数对象
 * @returns {Promise<boolean>}
 */
function handleAppointmentCase(self, dateRangeString, params) {
    const { verifyStateName } = params;

    if (verifyStateName === '审核通过') {
        return showConfirmationDialog(self, {
            title: `是否取消${dateRangeString}的摊位预约？`,
            action: 'cancelAppointment',
            params: params
        });
    } else if (verifyStateName === '待审核') {
        return showConfirmationDialog(self, {
            title: `是否撤销${dateRangeString}的申请？`,
            action: 'withdrawApplication',
            params: params
        });
    } else if (verifyStateName === '审核不通过') {
        return viewAppointmentDetails(params);
    }

    return Promise.resolve(false);
}

/**
 * 处理取消申请相关逻辑
 * @param {Object} self - 上下文
 * @param {string} dateRangeString - 日期范围字符串
 * @param {Object} params - 参数对象
 * @returns {Promise<boolean>}
 */
function handleCancellationCase(self, dateRangeString, params) {
    const { verifyStateName } = params;

    if (verifyStateName === '待审核') {
        return showConfirmationDialog(self, {
            title: `是否撤销${dateRangeString}的取消申请？`,
            action: 'withdrawCancellation',
            params: params
        });
    } else if (['审核通过', '审核不通过'].includes(verifyStateName)) {
        return viewCancellationDetails(params);
    }

    return Promise.resolve(false);
}

/**
 * 显示确认对话框
 * @param {Object} self - 上下文
 * @param {Object} options - 对话框选项
 * @param {string} options.title - 标题
 * @param {string} options.action - 操作类型
 * @param {Object} options.params - 参数对象
 * @returns {Promise<boolean>}
 */
function showConfirmationDialog(self, options) {
    return new Promise((resolve) => {
        self.$ztDialog.confirm({
            title: options.title,
            showConfirmButton: true,
            showCancelButton: true,
            cancelButtonText: "取消",
            confirmButtonText: "确定",
        }).then(() => {
            handleAction(options.action, options.params)
                .then(resolve)
                .catch(() => resolve(false));
        }).catch(() => {
            resolve(false);
        });
    });
}

/**
 * 执行对应操作
 * @param {string} action - 操作类型
 * @param {Object} params - 参数对象
 * @returns {Promise<boolean>}
 */
function handleAction(action, params) {
    const { id } = params;

    switch (action) {
        case 'cancelAppointment':
            return updateAppointmentStatus(id, -1, params);
        case 'withdrawApplication':
            return updateAppointmentStatus(id, -2, params);
        case 'withdrawCancellation':
            // 取消撤销申请
            return updateCancellationStatus(id, -2, params);
        default:
            return Promise.resolve(false);
    }
}

/**
 * 撤销 预约申请 状态变更 申请信息为已撤销 预约状态变更为审核通过
 * @param {string} id - 记录ID
 * @param {number} status - 状态值
 * @param {Object} params - 参数对象
 * @returns {Promise<boolean>}
 */
function updateAppointmentStatus(id, status, params) {
    console.log(`更新预约状态: ID=${id}, 状态=${status}`, params);

    const updateVerifySql = `UPDATE('ds_tbl:t_c3c221fc03ab45dc95813d7fc908a354', QUERY_EQ('id', ${id}), '', ['verify_state_id', '${status}'])`;
    const updateRecordSql = `UPDATE('ds_tbl:t_bff53c221c8c45898d6ce2809c4eb637', QUERY_EQ('appointment_verify_id', ${id}), '', ['appointment_state_id', '${status === -2 ? -2 : -1}'])`;

    return new Promise((resolve) => {
        api.EXEC_FORMULA(updateVerifySql)
            .then(() => api.EXEC_FORMULA(updateRecordSql))
            .then(() => {
                console.log("预约状态更新成功");
                resolve(true);
            })
            .catch((error) => {
                console.error("更新预约状态失败:", error);
                resolve(false);
            });
    });
}

/**
 * 撤销 取消预约申请状态变更 申请信息为已撤销 预约状态变更为审核通过
 * @param {string} id - 记录ID
 * @param {number} status - 状态值
 * @param {Object} params - 参数对象
 * @returns {Promise<boolean>}
 */
function updateCancellationStatus(id, status, params) {
    console.log(`更新取消申请状态: ID=${id}, 状态=${status}`, params);

    const updateSql = `UPDATE('ds_tbl:t_c3c221fc03ab45dc95813d7fc908a354', QUERY_EQ('id', ${id}), '', ['verify_state_id', '${status}'])`;
    const updateRecordSql = `UPDATE('ds_tbl:t_bff53c221c8c45898d6ce2809c4eb637', QUERY_EQ('remove_appointment_verify_id', ${id}), '', ['appointment_state_id', '1'])`;
    return new Promise((resolve) => {
        api.EXEC_FORMULA(updateSql)
            .then(() => api.EXEC_FORMULA(updateRecordSql))
            .then(() => {
                console.log("取消申请状态更新成功");
                resolve(true);
            })
            .catch((error) => {
                console.error("更新取消申请状态失败:", error);
                resolve(false);
            });
    });
}

/**
 * 查看预约申请详情
 * @param {Object} params - 参数对象
 * @returns {Promise<boolean>}
 */
function viewAppointmentDetails(params) {
    console.log('查看预约申请详情', params);
    // 这里添加实际查看详情的逻辑
    return Promise.resolve(true);
}

/**
 * 查看取消申请详情
 * @param {Object} params - 参数对象
 * @returns {Promise<boolean>}
 */
function viewCancellationDetails(params) {
    console.log('查看取消申请详情', params);
    // 这里添加实际查看详情的逻辑
    return Promise.resolve(true);
}
